// 设备预约
// react-native function组件
import React, {useEffect} from 'react';
import {
  View,
  Text,
  Dimensions,
  ToastAndroid,
  ImageBackground,
  Alert,
} from 'react-native';
import {useStyleConstants} from '../resources/StyleConstants';
import {useResponsive} from 'react-native-responsive-hook';
import {get, getBaseURL, post, postForm} from '../http/http';
import Row from '../components/Row';
import AutoSizingImage from '../components/AutoSizingImage';
import ReserveView from '../views/ReserveView';
import ColorButton from '../components/ColorButton';
import Colors from '../resources/Colors';
import qs from 'qs';
import ImageConstants from '../resources/ImageConstants';
import {launchImageLibrary} from 'react-native-image-picker';
import ReactNativeBlobUtil from 'react-native-blob-util';
import ModalViewUtil from '../components/ModalViewUtil';
import {TextInput} from 'react-native-gesture-handler';
import NumberInputView from '../views/NumberInputView';

const DeviceReserveScreen = ({navigation, route}) => {
  const {STYLES} = useStyleConstants();
  const {wp, hp, rem} = useResponsive();

  const warehousingId = route.params.warehousingId;
  const modelId = route.params.modelId;
  const [device, setDevice] = React.useState({});

  const [reserveTimeList, setReserveTimeList] = React.useState([]);
  useEffect(() => {
    const loadData = async () => {
      const {data} = await get(
        '/assets/assetsWarehousing/api/getAssetsWarehousingModelDetail',
        {
          warehousingId: warehousingId,
        },
      );
      setDevice(data);
    };
    const loadData2 = async () => {
      const {data} = await get(
        '/assets/equipmentApi/api/getEquipmentModelApi',
        {
          modelId: modelId,
        },
      );
      setDevice(data);
    };
    if (warehousingId) {
      loadData();
    }
    if (modelId) {
      loadData2();
    }
  }, []);

  const reserveByDate = async () => {
    if (reserveTimeList.length === 0) {
      ToastAndroid.show('请选择预约时间', ToastAndroid.SHORT);
      return;
    }
    try {
      const dateSet = new Set(reserveTimeList.map(v => v.split(' ')[0]));
      const pointStr = reserveTimeList.map(v => {
        return {
          startTime: v.split(' ')[1].split('-')[0],
          endTime: v.split(' ')[1].split('-')[1],
        };
      });
      if (device.appointmentCycle === 1) {
        if (dateSet.size > 1) {
          ToastAndroid.show('按小时预约预约不能跨天', ToastAndroid.SHORT);
          return;
        }
      }
      const {data} = await get(
        `/assets/assetsReserveOrder/api/submitAssetsReserveOrder?appointmentDate=${Array.from(
          dateSet,
        ).join(
          ',',
        )}&warehousingId=${warehousingId}&orderRemark=${''}&pointStr=${encodeURI(
          JSON.stringify(pointStr),
        )}`,
        {},
        true,
      );

      ToastAndroid.show('预约成功', ToastAndroid.SHORT);
      navigation.goBack();
    } catch (error) {
      ToastAndroid.show('预约失败:' + error.message, ToastAndroid.SHORT);
    }
  };

  const reserveByDeviceNo = async (isAppointTime: number, number: number) => {
    if (reserveTimeList.length === 0) {
      ToastAndroid.show('请选择预约时间', ToastAndroid.SHORT);
      return;
    }

    try {
      const dateSet = new Set(reserveTimeList.map(v => v.split(' ')[0]));
      const pointStr = reserveTimeList.map(v => {
        return {
          timeSt: v.split(' ')[1].split('-')[0],
          timeEn: v.split(' ')[1].split('-')[1],
        };
      });
      let count = dateSet.size;
      if (device.appointmentCycle === 1) {
        if (dateSet.size > 1) {
          ToastAndroid.show('按小时预约预约不能跨天', ToastAndroid.SHORT);
          return;
        }
        if (isAppointTime === 1) {
          ToastAndroid.show('按小时预约无法指定时间段', ToastAndroid.SHORT);
          return;
        }
      } else {
        count = pointStr.length;
      }
      const {data} = await post(
        `/assets/assetsReserveApply/api/userSubmitLineUpApply?modelId=${modelId}&orderRemark=${''}&isAppointTime=${isAppointTime}&appointmentNumber=${number}&appointmentDate=${Array.from(
          dateSet,
        ).join(',')}`,
        {},
        true,
      );
      ToastAndroid.show('预约成功', ToastAndroid.SHORT);
      navigation.goBack();
    } catch (error) {
      ToastAndroid.show('预约失败:' + error.message, ToastAndroid.SHORT);
    }
  };

  const alertTime = () => {
    Alert.alert('提示', '是否严格按照所选时间段提交预约？', [
      {
        text: '可按时间段提供',
        onPress: () => {
          ModalViewUtil.showFromCenter(
            <NumberInputView
              confirm={number => {
                reserveByDeviceNo(0, number);
                ModalViewUtil.dismissBottomView();
              }}
            />,
          );
          // reserveByDeviceNo(1);k
        },
        style: 'cancel',
      },
      {text: '按照所选时间段', onPress: () => reserveByDeviceNo(1)},
    ]);
  };

  return (
    <View style={{width: '100%', flex: 1}}>
      <ImageBackground
        source={ImageConstants.ICON_TOP_BG}
        resizeMode="cover"
        style={{width: '100%', alignItems: 'flex-start', marginBottom: 20}}>
        <Text
          style={{
            fontSize: STYLES.THIRD_FONT_SIZE,
            margin: STYLES.MARGIN_SPACE_2,
            color: 'white',
          }}>
          设备预约
        </Text>
        <Row style={{width: '100%', alignItems: 'flex-start'}}>
          <AutoSizingImage
            source={{uri: device.modelCover}}
            width={Dimensions.get('window').width * 0.2}
            style={{margin: STYLES.MARGIN_SPACE_2}}
          />
          <View
            style={{
              flex: 1,
              alignItems: 'flex-start',
              justifyContent: 'flex-start',
              marginVertical: hp(2),
            }}>
            <Text style={{fontSize: STYLES.FOURTH_FONT_SIZE, color: 'white'}}>
              {device.modelName}
            </Text>
            <Text style={{fontSize: STYLES.TEXT_FONT_SIZE, color: 'white'}}>
              {device.modelDescribe}
            </Text>
            {modelId ? (
              <Text style={{fontSize: STYLES.TEXT_FONT_SIZE, color: 'white'}}>
                发送方式:
                {device.grantWay === 1
                  ? '场内自助'
                  : device.grantWay === 2
                  ? '线下发放'
                  : '智能柜发放'}
              </Text>
            ) : null}
          </View>
        </Row>
      </ImageBackground>
      <ReserveView
        warehousingId={warehousingId}
        modelId={modelId}
        onReserveChange={setReserveTimeList}
      />
      <View
        style={{
          flexDirection: 'row',
          width: '100%',
          justifyContent: 'space-around',
        }}>
        <ColorButton
          onPress={modelId ? alertTime : reserveByDate}
          backgroundColor={'white'}
          title={'提交预约'}
          color={'black'}
          fontSize={rem(10)}
          height={hp(4)}
          containerStyle={{
            marginHorizontal: wp(1),
            marginBottom: hp(1),
            borderColor: '#CDD1D4',
            borderWidth: 1,
            width: wp(40),
          }}
        />
      </View>
    </View>
  );
};
export default DeviceReserveScreen;
